//
//  main.cpp
//  RWFileProj
//
//  Created by dhc on 14-10-24.
//  Copyright (c) 2014年 dhc. All rights reserved.
//

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

const std::string filePath("/Users/dhc/Desktop/stud.bin");

const std::string newFilePath("/Users/dhc/Desktop/tiles.bin");

typedef struct
{
    std::string name;
    int id;
    int age;
    char sex;
    
}Student;

void writeDataToFile();

void readDataFromFile();

int main(int argc, const char * argv[])
{
    FILE* fp = fopen(newFilePath.c_str(), "rw");
    if (!fp)
    {
        cout<<"open error"<<endl;
        abort();
    }
    fclose(fp);
    cout<<"open OK"<<endl;
    
    
    writeDataToFile();
    readDataFromFile();
    return 0;
}

void readDataFromFile()
{
    Student stud[3];
    int i;
    ifstream infile(filePath,ios::binary);
    if(!infile)
    {
        cerr<<"open error!"<<endl;
        abort( );
    }
    for(i=0;i<3;i++)
        infile.read((char*)&stud[i],sizeof(stud[i]));
    infile.close( );
    for(i=0;i<3;i++)
    {
        cout<<"NO."<<i+1<<endl;
        cout<<"name:"<<stud[i].name<<endl;
        cout<<"num:"<<stud[i].id<<endl;;
        cout<<"age:"<<stud[i].age<<endl;
        cout<<"sex:"<<stud[i].sex<<endl<<endl;
    }
}

void writeDataToFile()
{
    Student stud[3]={"Li",1001,18,'f',"Fun",1002,19,'m',"Wang",1004,17,'f'};
    ofstream outfile(filePath,ios::binary);
    if(!outfile)
    {
        cerr<<"open error!"<<endl;
        abort( );//退出程序
    }
    for(int i=0;i<3;i++)
        outfile.write((char*)&stud[i],sizeof(stud[i]));
    outfile.close( );
}
